import React, {Component} from 'react';
import PropTypes from 'prop-types';
import update from 'immutability-helper';

class BaseOpts extends Component {

    static propTypes = {
        data: PropTypes.object,
        dataChange: PropTypes.func,
    };

    constructor(props) {
        super(props);
    }

    $dataChange(key, val, ty) {
        this.setState((preState) => {
            var isSetArray = key instanceof Array;
            var keys = isSetArray ? key : [key];
            var vals = isSetArray ? val : [val];
            var newData;

            keys.forEach(function (key, i) {
                var val = vals[i];

                if (ty === false) {
                    newData = update(newData || preState.data, {
                        [`${key}`]: {
                            '$set': val
                        }
                    });
                } else {
                    ty = ty || 'dataset';
                    newData = update(newData || preState.data, {
                        [`${ty}`]: {
                            [`${key}`]: {
                                '$set': val
                            }
                        }
                    });
                }
            });

            this.props.dataChange && this.props.dataChange(newData);
            return {data: newData};
        });
    }

}

export default BaseOpts;
